package com.iqilu.ksd.activity;

import android.Manifest;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.iqilu.ksd.R;
import com.iqilu.ksd.adapter.CityAdapter;
import com.iqilu.ksd.bean.CityItemBean;
import com.iqilu.ksd.constant.Config;
import com.iqilu.ksd.event.CityChangeEvent;
import com.iqilu.ksd.utils.CityUtils;
import com.iqilu.ksd.utils.SPUtils;
import com.jaeger.library.StatusBarUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by Coofee on 2016/11/10.
 */

public class CityActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {

    private static final String TAG = "CityActivity";

    private ArrayList<CityItemBean> list;
    private CityAdapter adapter;

    private TextView tvTitle;
    private ImageView btLeft;
    private TextView tvCity;
    private TextView tvReload;
    private ListView lvList;

    private static final int PER_LOCATION = 1001;
    private AMapLocationClient locationClient = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_city);
        StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.blue_dark), Config.STATUSBAR_ALPHA);
        initView();
        list = CityUtils.getCityList();
        adapter = new CityAdapter(this);
        adapter.setData(list);
        lvList.setAdapter(adapter);

        startLocation();
    }

    private void initView() {
        tvTitle = getView(R.id.tv_title);
        tvTitle.setText(R.string.city_title);
        setZHTypeface(tvTitle);
        btLeft = getView(R.id.bt_left);
        tvCity = getView(R.id.tv_city);
        tvReload = getView(R.id.tv_reload);
        lvList = getView(R.id.lv_list);
        tvReload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLocation();
            }
        });
        lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CityItemBean item = CityUtils.getCityList().get(position);
                SPUtils.setPref(CityActivity.this, Config.CITY, item.getCityName());
                SPUtils.setPref(CityActivity.this, Config.CITY_ID, item.getCityId());
                EventBus.getDefault().post(new CityChangeEvent());
                finish();
            }
        });
        btLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @AfterPermissionGranted(PER_LOCATION)
    private void startLocation() {
        String perm = Manifest.permission.ACCESS_FINE_LOCATION;
        if (EasyPermissions.hasPermissions(this, perm)) {
            initLocation();
            locationClient.startLocation();
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.per_con_location), PER_LOCATION, perm);
        }
    }

    private void initLocation() {
        //初始化client
        locationClient = new AMapLocationClient(this.getApplicationContext());
        //设置定位参数
        locationClient.setLocationOption(getDefaultOption());
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
    }

    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        mOption.setHttpTimeOut(30000);
        mOption.setNeedAddress(true);
        mOption.setOnceLocation(true);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);
        return mOption;
    }

    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation loc) {
            if (null != loc && loc.getErrorCode() == 0) {
                //解析定位结果
                String city = loc.getCity();
                stopLocation();
                Toast.makeText(CityActivity.this, R.string.city_reload_success, Toast.LENGTH_SHORT).show();
                Log.i(TAG, "city=" + city);
                CityItemBean item = CityUtils.getCity(city);
                if (item.getCityId() == SPUtils.getPref(CityActivity.this, Config.CITY_ID, 0)) {
                    return;
                }
                SPUtils.setPref(CityActivity.this, Config.CITY, item.getCityName());
                SPUtils.setPref(CityActivity.this, Config.CITY_ID, item.getCityId());
                tvCity.setText(SPUtils.getPref(CityActivity.this, Config.CITY, ""));
                EventBus.getDefault().post(new CityChangeEvent());
            } else {
                Toast.makeText(CityActivity.this, R.string.city_reload_error, Toast.LENGTH_SHORT).show();
            }
        }
    };

    private void stopLocation() {
        locationClient.stopLocation();
    }

    private void destroyLocation() {
        if (null != locationClient) {
            locationClient.onDestroy();
            locationClient = null;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this, getString(R.string.per_con_location))
                    .setTitle(getString(R.string.per_title))
                    .setPositiveButton(getString(R.string.setting))
                    .setNegativeButton(getString(R.string.cancel), null)
                    .setRequestCode(requestCode)
                    .build()
                    .show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyLocation();
    }
}
